import os
import subprocess
from common.Del_old_Uril.file_remove import remove_file
from common.Del_old_Uril.del_log_util import delete_old_logs

# 当前路径(使用 abspath 方法可通过dos窗口执行)
current_path = os.path.dirname(os.path.abspath(__file__))
# json报告路径
json_report_path = os.path.join(current_path, './outFiles/report/json')
# html报告路径
html_report_path = os.path.join(current_path, './outFiles/report/html')

if __name__ == '__main__':
    # 运行前删除旧的report测试报告
    remove_file(file_path="outFiles/report/")
    # 保留days_to_keep=*天日志
    delete_old_logs(log_dir='outFiles/logs/', days_to_keep=3)

    # 定义要执行的YAML用例文件，可指定多个执行
    yaml_files = [
        'data/ctrler_yaml/UAT/test_vni_a.yaml',
        'data/ctrler_yaml/UAT/test_vni_b.yaml',
        'data/ctrler_yaml/UAT/test_logic_port.yaml',
        'data/ctrler_yaml/UAT/test_l2lan_a.yaml',
        'data/ctrler_yaml/UAT/test_l2lan_b.yaml',
        'data/ctrler_yaml/UAT/test_l2lan_c.yaml',
        'data/ctrler_yaml/UAT/test_l2lan_d.yaml',
        'data/ctrler_yaml/UAT/test_l2lan_update_bandwidth_a.yaml',
        'data/ctrler_yaml/UAT/test_l2lan_update_bandwidth_b.yaml',
        'data/ctrler_yaml/UAT/test_path_create_del_a.yaml',
        'data/ctrler_yaml/UAT/test_path_create_del_b.yaml',
        'data/ctrler_yaml/UAT/test_path_create_del_c.yaml',
        'data/ctrler_yaml/UAT/test_path_create_del_d.yaml'
    ]

    for index, yaml_file in enumerate(yaml_files):
        # 设置环境变量，指定当前测试用例文件执行
        os.environ['TEST_CASES_FILE'] = yaml_file

        print(f"_____run test_____：{yaml_file}")

        # 获取YAML文件的基本名称（不含路径和扩展名）作为报告的一部分
        yaml_base_name = os.path.splitext(os.path.basename(yaml_file))[0]

        # 为每个YAML文件创建独立的报告目录，目录名中包含YAML文件的名称，按照执行顺序排序
        json_report_path_specific = os.path.join(current_path, f'./outFiles/report/json/{index:02d}_report_{yaml_base_name}')
        html_report_path_specific = os.path.join(current_path, f'./outFiles/report/html/{index:02d}_report_{yaml_base_name}')

        # 确保报告目录存在
        os.makedirs(json_report_path_specific, exist_ok=True)
        os.makedirs(html_report_path_specific, exist_ok=True)

        # 使用subprocess调用pytest
        cmd = f'pytest -vs ./testCase/test_case_driver.py --alluredir={json_report_path_specific}'
        subprocess.run(cmd, shell=True)

        # 把json文件转成html报告，报告目录名包含YAML文件的名称
        cmd = f'allure generate {json_report_path_specific} -o {html_report_path_specific} --clean'
        subprocess.run(cmd, shell=True)

